
function results=OoSstudy(Y,ECON,REC,R,h)

P_0=0;
T=size(Y,1);
P=T-(R+P_0); % forecast evaluation period

FC_HA=zeros(P_0+P,1);
FC_ECON=zeros(P_0+P,1);
beta_ECON=zeros(P_0+P,1,2);

 for t=1:P_0+P; %loop for OoS calc
  
    FC_HA(t)=mean(Y(1+h:R+(t-1))); %loose some initial obs to compute h period returns
        
    X_t=ECON(1:R+(t-1)-h); 
    Y_t=Y(1+h:R+(t-1));
    
        RHS_i=[X_t(:) ones(R+(t-1)-h,1)];
        
        % Individual predictive regression forecasts
        [bv,sebv,R2v,R2vadj,v,F] = olsgmm(Y_t,RHS_i,h,-1); %no s.e. computation
        FC_ECON(t)=[ECON(R+(t-1),1) 1]*bv;
        beta_ECON(t,1,1)=bv(1);
        beta_ECON(t,1,2)=sebv(1);         
 end;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Forecast evaluation based on MSFE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

beta_ECON=beta_ECON(P_0+h:end,:,:);
actual=Y(R+P_0+h:end);
FC_HA=FC_HA(P_0+1:end-h+1);
FC_ECON=FC_ECON(P_0+1:end-h+1,:);

REC_table=REC(R+P_0:end-h,1); % recession dummies, 1994:01-2010:12
EXP_table=(ones(size(REC_table,1),1)-REC_table);
index_EXP=find(EXP_table);
index_REC=find(REC_table);

e_HA=actual-FC_HA;
e_ECON=kron(ones(1,1),actual)-FC_ECON;
R2OS_ECON=zeros(1,6);

    % Overall

    R2OS_ECON(1,1)=100*(1-(sum(e_ECON(:,1).^2)/sum(e_HA.^2)));
    f_i=e_HA.^2-(e_ECON(:,1).^2-(FC_HA-FC_ECON(:,1)).^2);   
    [bv,sebv,R2v,R2vadj,v,F] = olsgmm(f_i,ones(size(f_i,1),1),h,1);
    %R2OS_ECON(1,2)=1-normcdf(bv/sebv,0,1);
    R2OS_ECON(1,2)=bv/sebv;
    
    results.T=size(f_i,1);
    
    % Expansion

    R2OS_ECON(1,3)=100*(1-(sum(e_ECON(index_EXP,1).^2)/sum(e_HA(index_EXP).^2)));
    f_i=e_HA(index_EXP).^2-(e_ECON(index_EXP,1).^2-(FC_HA(index_EXP)-FC_ECON(index_EXP,1)).^2);
    [bv,sebv,R2v,R2vadj,v,F] = olsgmm(f_i,ones(size(f_i,1),1),h,1);
    %R2OS_ECON(1,4)=1-normcdf(bv/sebv,0,1);
    R2OS_ECON(1,4)=bv/sebv;

    % Recession

    R2OS_ECON(1,5)=100*(1-(sum(e_ECON(index_REC,1).^2)/sum(e_HA(index_REC).^2)));
    f_i=e_HA(index_REC).^2-(e_ECON(index_REC,1).^2-(FC_HA(index_REC)-FC_ECON(index_REC,1)).^2);
    [bv,sebv,R2v,R2vadj,v,F] = olsgmm(f_i,ones(size(f_i,1),1),h,1);
    %R2OS_ECON(1,6)=1-normcdf(bv/sebv,0,1);
    R2OS_ECON(1,6)=bv/sebv;

    results.R2OS=R2OS_ECON(1,1);
    results.R2OSexp=R2OS_ECON(1,3);
    results.R2OSrec=R2OS_ECON(1,5);

    results.CW=R2OS_ECON(1,2);
    results.CWexp=R2OS_ECON(1,4);
    results.CWrec=R2OS_ECON(1,6);
    
    
 
 
 
 